package com.ctrip.corp.obt.shard.sql.mybatis.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.ctrip.corp.obt.generic.utils.NumberUtils;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

/**
 * @author x.shen
 * @desc 类型转换器，实现jdbcType=tiny转Java=Boolean
 * @since 2023/10/30
 */
@MappedJdbcTypes({JdbcType.BIT})
public class IntToBitTypeHandler extends BaseTypeHandler<Integer> {
    /**
     * 插入时设置参数类型
     * @param ps
     * @param i
     * @param parameter
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Integer  parameter, JdbcType jdbcType) throws SQLException {
        ps.setByte(i,convertToBit(parameter));
    }

    /**
     * 获取时转换回的自定义类型，根据列名获取
     * @param rs
     * @param columnName
     * @return
     * @throws SQLException
     */
    @Override
    public Integer getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        int result = rs.getInt(columnName);
        return result == 0 && rs.wasNull() ? null : result;
    }

    @Override
    public Integer getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        int result = rs.getInt(columnIndex);
        return result == 0 && rs.wasNull() ? null : result;
    }

    @Override
    public Integer getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        int result = cs.getInt(columnIndex);
        return result == 0 && cs.wasNull() ? null : result;
    }

    private Byte convertToBit (Integer value) {
       if(value == 1){
           return new Byte("1");
       }else {
           return new Byte("0");
       }
    }
}
